from PyQt5.QtCore import pyqtSignal, QThread

from base_api.MessageClass import Message

"""
信号池
"""


class SignalPool(QThread):
    # 声明多个pyqtSignal对象，作为信号池。使用时判断获取对象，占用，使用后释放
    signal = pyqtSignal(object)
    signal_2 = pyqtSignal(object)
    signal_3 = pyqtSignal(object)
    signal_4 = pyqtSignal(object)
    signal_5 = pyqtSignal(object)
    # False表示对应信号位未被占用
    signal_flag_list = [False, False, False, False, False]

    def __init__(self):
        super().__init__()
        # 待执行的线程任务
        self.execute_method = None
        # 当前占用的信号位
        self.signal_this = None
        # 当前占用的信号位 对应索引
        self.signal_this_index = -1

    """
    获取pyqtSignal对象，获取成功返回True，获取失败返回False
    """
    def get_signal(self):
        # 所有信号位标志都为True，表示均被占用
        if all(self.signal_flag_list):
            return False
        if not self.signal_flag_list[0]:
            self.signal_this = self.signal
            self.signal_this_index = 0
        elif not self.signal_flag_list[1]:
            self.signal_this = self.signal_2
            self.signal_this_index = 1
        elif not self.signal_flag_list[2]:
            self.signal_this = self.signal_3
            self.signal_this_index = 2
        elif not self.signal_flag_list[3]:
            self.signal_this = self.signal_4
            self.signal_this_index = 3
        elif not self.signal_flag_list[4]:
            self.signal_this = self.signal_5
            self.signal_this_index = 4
        self.signal_flag_list[self.signal_this_index] = True
        return True

    def run(self):
        try:
            self.execute_method()
            # 正常执行结束
            self.signal_this.emit(Message(-1, ''))
        except Exception as e:
            # 异常执行结束
            self.signal_this.emit(Message(-2, str(e)))
        finally:
            # 释放消息位
            self.release()

    """
    释放当前对象占用的pyqtSignal对象
    """
    def release(self):
        if self.signal_this_index != -1:
            self.signal_flag_list[self.signal_this_index] = False
            self.signal_this_index = -1
            self.signal_this = None

    """
    输出方法
    """
    def output(self, data: object):
        self.signal_this.emit(Message(1, data))

